package org.example;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.example.utils.DBUtil;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo2_JDBC {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;

            try {
                // 1.获取数据库连接
                connection=DBUtil.getConnection();
                // 2.定义SQL语句
                String sql="insert into student(id,name,age,sex) values(?,?,?,?)";
                // 3. 预处理SQL语句
                statement=connection.prepareStatement(sql);
                // 4.接收参数
                System.out.println("请输入学生Id：");
                Scanner sc=new Scanner(System.in);
                int stuId=sc.nextInt();

                System.out.println("请输入学生姓名：");
                String stuName=sc.next();

                System.out.println("请输入学生年龄：");
                int stuAge=sc.nextInt();

                System.out.println("请输入学生性别：");
                String stuSex=sc.next();

                // 5. 用真实数据填充占位符
                statement.setInt(1,stuId);
                statement.setString(2,stuName);
                statement.setInt(3,stuAge);
                statement.setString(4,stuSex);
                // 6.执行SQL,并查询结果
                int row=statement.executeUpdate();
                if(row>0){
                    System.out.println("插入成功");
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                // 释放资源,关闭连接
                DBUtil.close(null, statement, connection);
            }
    }
}
